package com.joesem.sale.client.logic.workOrder

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.goodPermission.expansion.launchCamera
import com.goodPermission.expansion.launchPic
import com.goodPermission.permission.launchPermission
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.ActivityOrderCompleteBinding
import com.jiaxing.sale.client.databinding.ItemHeaderOrderDetailsRetureBinding
import com.jiaxing.sale.client.databinding.ItemImgBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.viewModel.OrderCompleteViewModel
import com.joesem.sale.client.network.data.ReceiptMode
import com.joesem.sale.client.network.data.UploadImgMode
import com.joesem.sale.client.utils.activityResult.launcherResult
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.*


class OrderCompleteActivity : BaseActivity<ActivityOrderCompleteBinding>() {

    private val viewModel by createViewModel<OrderCompleteViewModel>()

    private val values = hashMapOf<String, Any?>()

    private val serviceAdapter = object :
        BaseQuickAdapter<ReceiptMode.ServiceMode, BaseViewHolder>(R.layout.item_order_complete_service) {
        override fun convert(holder: BaseViewHolder, item: ReceiptMode.ServiceMode) {
            holder.setText(R.id.tvContent, item.name.orEmpty())
            holder.setText(R.id.tvUnit, item.unit.orEmpty())
            holder.setText(R.id.tvPrice, item.cost.toString())

            holder.getView<EditText>(R.id.tvContent).apply {
                addTextChangedListener {
                    item.name = it.toString()
                }
            }
            holder.getView<EditText>(R.id.tvNum).apply {
                setText(item.count.toString())
                setSelection(item.count.toString().length)
                addTextChangedListener {
                    item.count = it.toString()
                }
            }
            holder.getView<TextView>(R.id.tvUnit).click {
                optionParams(supportFragmentManager, PROJECT_UNITS, "请选择单位") {
                    item.unit = it
                    notifyItemChanged(holder.adapterPosition)
                }
            }
            holder.getView<EditText>(R.id.tvPrice).addTextChangedListener {
                item.cost = it.toString()
            }
            holder.getView<TextView>(R.id.btnDelete).click {
                remove(item)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
    }

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = "工单回执"
    }

    override fun ActivityOrderCompleteBinding.initView(savedInstanceState: Bundle?) {
        values["images"] = selectedImage.map { it.path }//初始化一下图片参数不然接口要报错
        rvServiceContent.adapter = serviceAdapter
        serviceAdapter.addHeaderView(
            ItemHeaderOrderDetailsRetureBinding.inflate(
                LayoutInflater.from(this@OrderCompleteActivity)
            ).apply {
                tvAction.visible()
            }.root
        )
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun ActivityOrderCompleteBinding.initListener() {
        btnReason.click {
            optionParams(supportFragmentManager, RECEIPT_REASON, "选择故障原因") {
                values["reason"] = it
                tvReason.text = it
                tvReason.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null)
            }
        }
        btnMode.click {
            optionParams(supportFragmentManager, RECEIPT_TYPE, "选择处理方式") {
                values["process_type"] = it
                tvMode.text = it
                tvMode.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null)
            }
        }
        etDetailsContent.addTextChangedListener {
            values["description"] = it?.toString().orEmpty()
        }
        btnImgAdd.click {
            picDialog(this@OrderCompleteActivity, pic = {
                launchPic("order" to "order_${System.currentTimeMillis()}.jpg") {
                    it.file?.let { it1 -> viewModel.uploadFile(it1) }
                }
            }, camera = {
                launchCamera("order" to "order_${System.currentTimeMillis()}.jpg") {
                    it.file?.let { it1 -> viewModel.uploadFile(it1) }
                }
            })
        }
        btnServiceItems.click {
            serviceAdapter.data.add(ReceiptMode.ServiceMode())
            serviceAdapter.notifyDataSetChanged()
        }
        rbRating1.setOnRatingChangeListener { _, fl, b ->
            when (fl) {
                1f -> "非常差"
                2f -> "差"
                3f -> "一般"
                4f -> "好"
                5f -> "非常好"
                else -> ""
            }.apply {
                tvRating1.text = this
                values["satisfaction"] = fl
            }

        }
        rbRating2.setOnRatingChangeListener { _, fl, b ->
            when (fl) {
                1f -> "极差"
                2f -> "一般"
                3f -> "良好"
                4f -> "满意"
                5f -> "非常满意"
                else -> ""
            }.apply {
                tvRating2.text = this
                values["attitude"] = fl
            }
        }
        rbRating3.setOnRatingChangeListener { _, fl, b ->
            when (fl) {
                1f -> "很慢"
                2f -> "慢"
                3f -> "一般"
                4f -> "快"
                5f -> "非常快"
                else -> ""
            }.apply {
                tvRating3.text = this
                values["efficiency"] = fl
            }
        }
        tvStartSignature.click {
            tvStartSignature.gone()
            llSignatureButton.visible()
            pvSignature.isPaint(true)
        }
        btnSignatureRest.click {
            pvSignature.clear()
            values["signature"] = null
        }
        btnSignatureConfirm.click {
            if (pvSignature.isPaintComplete()) {
                launchPermission(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    Manifest.permission.READ_MEDIA_IMAGES
                } else {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                }) {
                    if (it) {
                        bind.apply {
                            viewModel.saveSignature(pvSignature.getPaintBitmap())
                        }
                    } else {
                        toast("需要文件读写权限")
                    }
                }
            } else {
                toast("请签写完整哦")
            }
        }
        btnComplete.click {
            values["services"] = serviceAdapter.data
            viewModel.orderReceipt(intent?.getStringExtra("orderId"), values, serviceAdapter.data)
            Log.i("打印", "参数: $values")
        }

    }


    override fun ActivityOrderCompleteBinding.initIntent(intent: Any?) {
        when (intent) {
            is OrderCompleteViewModel.SignatureUploadIntent -> {
                tvStartSignature.visible()
                tvStartSignature.text = ""
                llSignatureButton.gone()
                pvSignature.isPaint(false)
                values["signature"] = intent.file.path
            }
            is OrderCompleteViewModel.ImgUploadIntent -> {
                addImageItem(intent.file)
            }
            is OrderCompleteViewModel.OrderReceiptIntent -> {
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    private val selectedImage = arrayListOf<UploadImgMode>()
    private fun addImageItem(file: UploadImgMode) {
        selectedImage.add(file)
        values["images"] = selectedImage.map { it.path }
        if (bind.cgImg.childCount >= 2) {
            bind.btnImgAdd.gone()
        }
        val itemBind = ItemImgBinding.inflate(LayoutInflater.from(this))
        itemBind.btnImgDelete.click {
            selectedImage.remove(file)
            values["images"] = selectedImage.map { it.path }
            bind.cgImg.removeView(itemBind.root)
            bind.btnImgAdd.visible()
        }
        Glide.with(this).load(file.url).into(itemBind.btnImg)
        itemBind.btnImg.click {
            imagePreview(
                this,
                supportFragmentManager,
                selectedImage.map { it.url.orEmpty() },
                selectedImage.indexOfFirst { it.url == file.url })
        }
        bind.cgImg.addView(itemBind.root, 0)
    }
}

fun optionOrderComplete(context: AppCompatActivity, id: String?, result: () -> Unit) {
    context.launcherResult<OrderCompleteActivity>("orderId" to id) { _, _ ->
        result.invoke()
    }
}